﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Configuration;
using IronOne.SalesOne.BusinessObjects;

namespace IronOne.SalesOne.DataObjects
{
    public class LinqTask
    {
        public int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]);

        public List<Task> GetTasks(string sortExpression)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<TaskEntity> query = db.TaskEntities;

                if (sortExpression.Length > 0)
                {
                    string[] sort = sortExpression.Split(' ');
                    string sortColumn = sort[0];
                    string sortOrder = sort[1];

                    switch (sortColumn)
                    {
                        case "TaskId":
                            if (sortOrder == "ASC")
                                query = query.OrderBy(c => c.TaskId);
                            else
                                query = query.OrderByDescending(c => c.TaskId);
                            break;
                        case "TaskName":
                            if (sortOrder == "ASC")
                                query = query.OrderBy(c => c.TaskName);
                            else
                                query = query.OrderByDescending(c => c.TaskName);
                            break;
                      
                    }
                }
                return query.Select(c => Mapper.ToTaskObject(c)).ToList();
            }
        }

        public List<Task> GetTasks(string sortExpression,int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<TaskEntity> query = db.TaskEntities;

                if (sortExpression.Length > 0)
                {
                    string[] sort = sortExpression.Split(' ');
                    string sortColumn = sort[0];
                    string sortOrder = sort[1];

                    switch (sortColumn)
                    {
                        case "TaskId":
                            if (sortOrder == "ASC")
                                query = query.OrderBy(c => c.TaskId);
                            else
                                query = query.OrderByDescending(c => c.TaskId);
                            break;
                        case "TaskName":
                            if (sortOrder == "ASC")
                                query = query.OrderBy(c => c.TaskName);
                            else
                                query = query.OrderByDescending(c => c.TaskName);
                            break;

                    }
                }
                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.Select(c => Mapper.ToTaskObject(c)).ToList();
            }
        }

        public List<Task> GetTasksForRole(Guid roleId)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<TaskEntity> query = db.TaskEntities;

                query = from p in db.TaskEntities
                        join tp in db.TaskPermissionEntities
                        on p.TaskId
                        equals tp.TaskId
                        where tp.RoleId == roleId
                        select p;
                        
               
                return query.Select(c => Mapper.ToTaskObject(c)).ToList();
            }
        }

        public List<Task> GetTasksForModule(Module module)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<TaskEntity> query = db.TaskEntities;

                query = from p in db.TaskEntities
                        join tim in db.TasksInModuleEntities
                        on p.TaskId
                        equals tim.TaskId
                        where tim.ModuleId==(short)module.ModuleId
                        select p;


                return query.Select(c => Mapper.ToTaskObject(c)).Distinct().ToList();
            }
        }

        public List<Page> GetPagesForTask(Task task)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<PagesInTaskEntity> query = from p in db.PagesInTaskEntities
                        where p.TaskId == (short)task.TaskId
                        select p;


                return query.Select(c => Mapper.ToPageObject(c)).Distinct().ToList();
            }
        }


        public string  GetPermissions(Guid roleId,int taskId)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    IQueryable<TaskPermissionEntity> query = db.TaskPermissionEntities;

                    var permissions = from p
                            in db.TaskPermissionEntities
                                      where p.TaskId == taskId & p.RoleId == roleId
                                      select new
                                      {
                                          p.Permissions,
                                      };
                    return permissions.SingleOrDefault().ToString();
                }
                catch (NullReferenceException)
                {
                    throw new Exception("No records found.");
                }
                catch(Exception) 
                {
                    return "";
                }
               
            }
        }

        public int UpdatePermissions(Guid roleId, int taskId,string permissions)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                
                try
                {
                    var taskPermission = from p
                           in db.TaskPermissionEntities
                                      where p.TaskId == taskId & p.RoleId == roleId
                                      select p;

                    foreach(TaskPermissionEntity ent in taskPermission)
                    {
                        ent.Permissions = permissions;
                        //db.SubmitChanges();
                    }

                    db.SubmitChanges();
                    return 1;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to permission record was made before your changes.");
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }

        public int UpdatePermissions(TaskCredentials taskCredentials)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    TaskPermissionEntity entity = Mapper.ToTaskPermissionEntity(taskCredentials);
                    db.TaskPermissionEntities.Attach(entity, true);
                    db.SubmitChanges();
                    return 1;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to  record was made before your changes.");
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }

        public void InsertPermission(TaskCredentials taskCredentials)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    TaskPermissionEntity entity = Mapper.ToTaskPermissionEntity(taskCredentials);
                    db.TaskPermissionEntities.InsertOnSubmit(entity);
                    db.SubmitChanges();

                    //message.Message_ID = entity.MessageId;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to permission record was made before your changes.");
                }
                catch (Exception)
                {
                    throw new Exception("Unable to insert a task permission.");
                }
            }
        }
    }
}
